package com.example.autopia.model.Repositories

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.Parking
import com.example.autopia.model.Item.Place
import com.example.autopia.model.Item.Transaction
import com.example.autopia.utilities.KEY_BD_TRANSACTIONS
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class TransactionRepository {
    private val database = FirebaseDatabase.getInstance()
    private var reference = database.getReference(KEY_BD_TRANSACTIONS)

    fun addTransaction(transaction: Transaction): Boolean {
        var status = false
        val newItem = reference.push()
        transaction.id = newItem.key ?: ""
        newItem.setValue(transaction)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }
    fun setUnActive(transactionId:String, cardId:String) : Boolean {
        var status = false
        reference.child(transactionId).child("active").setValue(false)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        reference.child(transactionId).child("cardId").setValue(cardId)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun getAllItems() : MutableLiveData<ArrayList<Transaction>>{
        val result: MutableLiveData<ArrayList<Transaction>> = MutableLiveData()
        val itemsList = ArrayList<Transaction>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children) {
                    val id = itemSnapshot.child("id").value.toString()
                    val status = itemSnapshot.child("place").child("status").value.toString().toInt()
                    val placeId = itemSnapshot.child("place").child("id").value.toString()
                    val userId = itemSnapshot.child("place").child("userId").value.toString()
                    val car = itemSnapshot.child("place").child("car").getValue(Car::class.java)
                    val place = Place(placeId,status,car,userId)
                    val namePark = itemSnapshot.child("namePark").value.toString()
                    val idPark = itemSnapshot.child("idPark").value.toString()
                    val active = itemSnapshot.child("active").value.toString().toBoolean()
                    val price = itemSnapshot.child("price").value.toString().toInt()
                    val startTime = itemSnapshot.child("startTime").value.toString().toInt()
                    val endTime = itemSnapshot.child("endTime").value.toString().toInt()
                    val cardId = itemSnapshot.child("cardId").value.toString()
                    val transaction = Transaction(id, place, namePark, idPark,active,price, startTime, endTime, cardId)
                    itemsList.add(transaction)
                }
                result.value = itemsList
            }
            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в Transactions")
            }
        })
        return result
    }
    fun getTransactionById(transactionId: String): MutableLiveData<Transaction> {
        val result: MutableLiveData<Transaction> = MutableLiveData()
        reference.child(transactionId).addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                if (dataSnapshot.exists()){
                    val id = dataSnapshot.child("id").value.toString()
                    val status = dataSnapshot.child("place").child("status").value.toString().toInt()
                    val placeId = dataSnapshot.child("place").child("id").value.toString()
                    val userId = dataSnapshot.child("place").child("userId").value.toString()
                    val car = dataSnapshot.child("place").child("car").getValue(Car::class.java)
                    val place = Place(placeId,status,car,userId)
                    val namePark = dataSnapshot.child("namePark").value.toString()
                    val idPark = dataSnapshot.child("idPark").value.toString()
                    val active = dataSnapshot.child("active").value.toString().toBoolean()
                    val price = dataSnapshot.child("price").value.toString().toInt()
                    val startTime = dataSnapshot.child("startTime").value.toString().toInt()
                    val endTime = dataSnapshot.child("endTime").value.toString().toInt()
                    val cardId = dataSnapshot.child("cardId").value.toString()
                    val transaction = Transaction(id, place, namePark, idPark,active,price, startTime, endTime, cardId)
                    result.value = transaction
                }
            }
            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в Transactions")
            }
        })
        return result
    }
    fun changeTransaction(transactionId: String, transaction: Transaction): Boolean {
        var status = false
        reference.child(transactionId).setValue(transaction).addOnCompleteListener {
            status = true
        }.addOnFailureListener { err ->
        }
        return status
    }
    fun getTransactionsByUserId(curUserId: String): MutableLiveData<ArrayList<Transaction>>{
        val itemsList = ArrayList<Transaction>()
        val result = MutableLiveData<ArrayList<Transaction>>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children){
                    val id = itemSnapshot.child("id").value.toString()
                    val idPark = itemSnapshot.child("idPark").value.toString()
                    val active = itemSnapshot.child("active").value.toString().toBoolean()
                    val placeId = itemSnapshot.child("place").child("id").value.toString()
                    val status = itemSnapshot.child("place").child("status").value.toString().toInt()
                    val userId = itemSnapshot.child("place").child("userId").value.toString()
                    val car = itemSnapshot.child("place").child("car").getValue(Car::class.java)
                    val place = Place(placeId,status,car,userId)
                    val namePark = itemSnapshot.child("namePark").value.toString()
                    val price = itemSnapshot.child("price").value.toString().toInt()
                    val startTime = itemSnapshot.child("startTime").value.toString().toInt()
                    val endTime = itemSnapshot.child("endTime").value.toString().toInt()
                    val cardId = itemSnapshot.child("cardId").value.toString()
                    val transaction = Transaction(id, place, namePark, idPark,active,price, startTime, endTime, cardId)
                    if (curUserId==userId){
                        itemsList.add(transaction)
                    }
                }
                result.value = itemsList
            }
            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в Transactions")
            }
        })
        return result
    }

    fun getActiveTransactionsByUserId(curUserId: String): MutableLiveData<Transaction>{
        val result = MutableLiveData<Transaction>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children){
                    val id = itemSnapshot.child("id").value.toString()
                    val idPark = itemSnapshot.child("idPark").value.toString()
                    val active = itemSnapshot.child("active").value.toString().toBoolean()
                    val placeId = itemSnapshot.child("place").child("id").value.toString()
                    val status = itemSnapshot.child("place").child("status").value.toString().toInt()
                    val userId = itemSnapshot.child("place").child("userId").value.toString()
                    val car = itemSnapshot.child("place").child("car").getValue(Car::class.java)
                    val place = Place(placeId,status,car,userId)
                    val namePark = itemSnapshot.child("namePark").value.toString()
                    val price = itemSnapshot.child("price").value.toString().toInt()
                    val startTime = itemSnapshot.child("startTime").value.toString().toInt()
                    val endTime = itemSnapshot.child("endTime").value.toString().toInt()
                    val cardId = itemSnapshot.child("cardId").value.toString()
                    val transaction = Transaction(id, place, namePark, idPark,active,price, startTime, endTime, cardId)
                    if (curUserId==userId && active){
                        result.value = transaction
                    }
                }
            }
            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в Transactions")
            }
        })
        return result
    }
    fun getTransactionByPlace(curPlace: Place,parkingId : String, curUserId : String): MutableLiveData<Transaction> {
        val result: MutableLiveData<Transaction> = MutableLiveData()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children){
                    val id = itemSnapshot.child("id").value.toString()
                    val idPark = itemSnapshot.child("idPark").value.toString()
                    val active = itemSnapshot.child("active").value.toString().toBoolean()
                    val placeId = itemSnapshot.child("place").child("id").value.toString()
                    val status = itemSnapshot.child("place").child("status").value.toString().toInt()
                    val userId = itemSnapshot.child("place").child("userId").value.toString()
                    val car = itemSnapshot.child("place").child("car").getValue(Car::class.java)
                    val place = Place(placeId,status,car,userId)
                    val namePark = itemSnapshot.child("namePark").value.toString()
                    val price = itemSnapshot.child("price").value.toString().toInt()
                    val startTime = itemSnapshot.child("startTime").value.toString().toInt()
                    val endTime = itemSnapshot.child("endTime").value.toString().toInt()
                    val cardId = itemSnapshot.child("cardId").value.toString()
                    val transaction = Transaction(id, place, namePark, idPark,active,price, startTime, endTime, cardId)
                    if (active && parkingId==idPark && curPlace.id ==placeId && curUserId==userId){
                        result.value = transaction
                    }
                }
            }
            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro","Ошибка в Transactions")
            }
        })
        return result
    }
    fun removeTransaction(transactionId: String): Boolean {
        var status = false
        reference.child(transactionId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }
}